//
//  LoadingView.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/6/22.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
class LoadingView: NSObject {
    var delay: Double = 150.0  //延迟时间 s
    var container:UIView!
    var bufWindows: [UIWindow] = []    //缓存window
    //显示loading框 x,y转圈图片位置(本项目中图片上传中使用)
    func showLoadingView(x:CGFloat,y:CGFloat) {
        let rootRect = UIApplication.shared.windows.first?.frame
        container = UIView()   //父容器
        container.frame = rootRect!
        container.backgroundColor = alphaBg
        //转圈
        let indicatorLength: CGFloat = 30.0   //正方形
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        indicatorView.frame = CGRect(x: x, y: y, width: indicatorLength, height: indicatorLength)
        indicatorView.startAnimating()
        container.addSubview(indicatorView)
        
        let window = UIWindow()
        window.backgroundColor = UIColor.clear   //全透明
        window.frame = rootRect!   //全屏大小
        window.windowLevel = UIWindowLevelAlert
        window.isHidden = false
        window.addSubview(container)
        perform(#selector(showFinished(sender:)), with: window, afterDelay: delay)
        bufWindows.append(window)
    }
    //居中显示图片类似点击放大查看
    func loadingPic(image:UIImage){
        let rootRect = UIApplication.shared.windows.first?.frame
        let window = UIWindow()
        window.backgroundColor = UIColor.clear   //全透明
        window.frame = rootRect!   //全屏大小
        window.windowLevel = UIWindowLevelAlert
        window.isHidden = false
        
        let container = UIView()   //父容器
        container.frame = rootRect!
        container.backgroundColor = alphaBg
        window.addSubview(container)
        //图片
        let imgView = UIImageView()
        imgView.image = image
        container.addSubview(imgView)
        imgView.snp.makeConstraints { (make) in
            make.center.equalTo(container.snp.center)
            make.width.equalTo(kScreenW - 20)
            make.height.equalTo(0.6*(kScreenW - 20))
        }
        //添加点击事件
        container.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGesture(sender:))))
        perform(#selector(showFinished(sender:)), with: window, afterDelay: delay)
        bufWindows.append(window)
    }
    //添加点击事件
    func tapGesture(sender: UITapGestureRecognizer) {
        //移除最后一个
        closeWin()
    }
    //toast超时关闭
    func showFinished(sender: AnyObject) {
        if let window = sender as? UIWindow {
            if let index = bufWindows.index(of: window) {
                bufWindows.remove(at: index)  //删除
            }
        }
    }
    //在超时前手动去关闭
    func closeWin(){
        //移除最后一个
        if bufWindows.count > 0 {
            bufWindows.removeLast()
        }
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }
}
